from Tkinter import Frame, Button,Listbox
from Tkconstants import YES, BOTH, END, LEFT
import os
import subprocess
import configuration

def frame(root, side):
    w = Frame(root)
    w.pack(side=side, expand=YES, fill=BOTH)
    return w

def button(root, side, text, command=None):
    w = Button(root, text=text, command=command)
    w.pack(side=side, expand=YES, fill=BOTH)
    return w

class Console():
    def __init__(self,name,path_icon,emulator_path,extension,path_rom):
        self.name = name
        self.icon = path_icon
        self.emulator = emulator_path
        self.ext  = extension
        self.rom  = path_rom
        self.games = list()
    
    def addGame(self,game):
        self.games.append(game)
        
        
class Game():
    def __init__(self,name,root,console):
        self.root = root
        self.name = name
        self.console = console
        pass
    def __str__(self):
        return self.name + '-' + self.root
        
class RomLoader():
    def load(self):
        self.consoles = list()
        for i in range(1,4):
            consoleDict = configuration.consoles['console_'+str(i)]
            console = Console(consoleDict['name'],consoleDict['icon'],consoleDict['emulator'],consoleDict['extension'],consoleDict['roms'])
            self.consoles.append(console)
        print self.consoles
        for console in self.consoles:
            print console.rom
            for (root, dirs, files) in os.walk(console.rom):
                    for file in files:
                        if file.endswith(console.ext):
                            print root + '/' + file
                            console.addGame(Game(file,root,console))
class Emulator(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.pack(expand=YES, fill=BOTH)
        self.master.title('Emulator@MEGAJANDRO')
        self.listBox = Listbox(self, width=50)
        self.listBox.bind("<Double-1>", self.click)
        self.listBox.pack()
        self.games = list()
        romLoader=RomLoader()
        romLoader.load()
        button = Button(self, text='All',command=self.allGames)
        button.pack(side=LEFT)
        for console in romLoader.consoles:
            button = Button(self, text=console.name)
            button.pack(side=LEFT)
            def handler(event, self=self, label=console.name):
                return self.btn_clicked(event, label)
            # respond to left mouse click
            button.bind('<1>', handler)
            self.__loadListBox__(console.games)
    
    def allGames(self):
        print 'List All games'
        self.listBox.delete(0, END)
        self.__loadListBox__(self.games,'All')
        
    def __loadListBox__(self,games,filterListBox=None):
        for game in games:
                if filterListBox:
                    if game.console.name == filterListBox:
                        self.listBox.insert(END, game)
                    elif filterListBox == 'All':
                        self.listBox.insert(END, game)
                else:    
                    self.listBox.insert(END, game)
                    self.games.append(game)
        
    def btn_clicked(self, event, label):
        """action code when button is clicked"""
        s = "you clicked button: " + label
        print s
        self.listBox.delete(0, END)
        self.__loadListBox__(self.games, label)
          
         
    def click(self, event):
        print("Clicked at: ", event.x, event.y)
        items = self.listBox.curselection()
        try:
            items = map(int, items)
        except ValueError: pass
        items = map(lambda i,d=self.games: d[i], items)
        if items:
            romPath = items[0].root + "/" + items[0].name
            matches = [x for x in items[0].console.emulator if x == romPath]
            if not matches : items[0].console.emulator.insert(1,romPath)
            print items[0].console.emulator
            subprocess.check_call(items[0].console.emulator) 
            
if __name__ == '__main__':
    Emulator().mainloop()
    
